(function($){
	
	$(function(){

		var controlsPrev = null;
		var controlsNext = null;

		var gallery = $("<div id='osmio-modal-gallery-light'></div>").appendTo("body");

		gallery.osmioModal({
			padding: [40, 40, 40, 40],
			minWidth: 100,
			minHeight: 100
		});
		
		gallery.osmioModalMedia({
			newWindow: false
		});

		gallery.osmioModal("exec", function(modal){

			modal.elements.wrapper.attr("id", "osmio-modal-gallery-light-wrapper");

			var controlsPrev = $("<a href='#' class='osmio-modal-gallery-light-control' id='osmio-modal-gallery-light-control-prev'>&larr;</a>").appendTo(modal.elements.container);
			var controlsNext = $("<a href='#' class='osmio-modal-gallery-light-control' id='osmio-modal-gallery-light-control-next'>&rarr;</a>").appendTo(modal.elements.container);

			$("a.osmio-modal-gallery-light").click(function(e){

				e.preventDefault();

				var self = $(this);

				$("#osmio-modal-gallery-light").osmioModalMedia(self.attr("href"), self.attr("title"), self.attr("link"));

				var links = $("a.osmio-modal-gallery-light").filter("a[rel=" + self.attr("rel") + "]").data("osmio-modal-gallery-light-current", false);
				self.data("osmio-modal-gallery-light-current", true);

				var prev = false;
				var next = false;
				var nextCatch = false;
				var prevCatch = false;

				links.each(function(){

					if (nextCatch) next = $(this);

					if ($(this).data("osmio-modal-gallery-light-current")) {

						nextCatch = true;
						prev = prevCatch;

					} else {

						nextCatch = false;

					}

					prevCatch = $(this);

				});

				controlsPrev.unbind("click");
				controlsNext.unbind("click");

				if (prev) {

					controlsPrev.removeClass("osmio-modal-gallery-light-controls-disabled").click(function(e){
						e.preventDefault();
						if (!$(this).hasClass("osmio-modal-gallery-light-controls-disabled")) prev.click();
					})

				} else {

					controlsPrev.addClass("osmio-modal-gallery-light-controls-disabled");

				}

				if (next) {

					controlsNext.removeClass("osmio-modal-gallery-light-controls-disabled").click(function(e){
						e.preventDefault();
						if (!$(this).hasClass("osmio-modal-gallery-light-controls-disabled")) next.click();
					})

				} else {

					controlsNext.addClass("osmio-modal-gallery-light-controls-disabled");

				}

				return false;

			});

		});

	});

})(jQuery);